<?php
header("Access-Control-Allow-Origin:*");
function wtype($pars){
	$status=0;
	try{
		$list=array(array('item'=>'疏港业务'),array('item'=>'空箱'),array('item'=>'重箱'),array('item'=>'门点业务'));
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

function checkbox($pars){
	$status=0;
	try{
		$db = &db();
		$list = array('if_order'=>0);
		$uid=$pars->uid?$pars->uid:0;
		$sid=$pars->sid?intval($pars->sid):0;//船公司
		$station=$pars->station?$pars->station:'';//场站
		$box=$pars->box?$pars->box:'';//箱型
		$quantity=$pars->quantity?$pars->quantity:'';//箱量
		if(empty($uid))
		throw new Exception("用户不存在！");
		if(empty($sid))
		throw new Exception("船名不能为空！");

		if(empty($station)){
			throw new Exception("场站不能为空！");
		}
		if(empty($box)){
			throw new Exception("箱型不能为空！");
		}
		if(empty($quantity)){
			throw new Exception("箱量不能为空！");
		}

		$sql = "select * from zys_member where user_id = '".$uid."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception('用户不存在');
		}
		$sql="select sid,code,sname from zys_shippingline where sid='".$sid."'";
		$row=$db->getRow($sql);
		if(empty($row)){
			throw new Exception("船公司不存在！");
		}

		$cc=substr($box, 0,2);
		$xx=substr($box, 2,2);

		$m=&m("member");
		$user=$m->get($uid);

		$url=APIURL.'flag=C&cus_no='.$row['code'].'&cc='.$cc.'&xx='.$xx.'&qty='.$quantity.'&cz_no='.$station.'&yy_no=&td_no=&ship_no=&ovoy=&tx_dd=
		&rem=&plate_no=&tel=&usr='.$user['user_name'];

		$retval=file_get_contents($url);
		$retval=json_decode($retval,true);
		if(empty($retval)){
			throw new Exception("操作失败，请重试！");
		}

		$rut=$retval['ClientRut'][0][0];
		if(empty($rut)){
			throw new Exception("操作失败，请重试！");
		}

		if(empty($rut['flag'])){
			throw new Exception($rut['rem']);
		}


		//调接口  todo
		$status=1;
		$list = array('if_order'=>1,'yy_no'=>$rut['yy_no']);
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 下预约订单
 * @param $pars
 */
function addorderbox($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$user_id=$pars->uid?$pars->uid:0;
		$vhccode=$pars->vhccode?$pars->vhccode:'';//车牌号
		$tel=$pars->tel?$pars->tel:'';//电话
		$sid=$pars->sid?intval($pars->sid):0;
		$station=$pars->station?$pars->station:'';//场站
		$box=$pars->box?$pars->box:'';//箱型
		$quantity=$pars->quantity?$pars->quantity:'';//箱量
		$ship_name=$pars->ship_name?$pars->ship_name:'';//船名
		$voyage=$pars->voyage?$pars->voyage:'';//船次
		$bill=$pars->bill?$pars->bill:'';//提单号
		$th_time=$pars->th_time?$pars->th_time:'';//提货时间
		$yy_no=$pars->yy_no?$pars->yy_no:'';//预约单号
		$rem=$pars->rem?$pars->rem:'';//备注
		if(empty($user_id))
		throw new Exception("用户不存在！");
		if(empty($sid))
		throw new Exception("船名不能为空！");

		if(empty($station)){
			throw new Exception("场站不能为空！");
		}
		if(empty($box)){
			throw new Exception("箱型不能为空！");
		}
		if(empty($quantity)){
			throw new Exception("箱量不能为空！");
		}
		if(empty($vhccode)){
			throw new Exception("车牌号不能为空！");
		}
		if(empty($tel)){
			throw new Exception("电话不能为空！");
		}
		if(empty($ship_name)){
			throw new Exception("船名不能为空！");
		}
		if(empty($voyage)){
			throw new Exception("船次不能为空！");
		}
		if(empty($bill)){
			throw new Exception("提单号不能为空！");
		}
		if(empty($th_time)){
			throw new Exception("提货时间不能为空！");
		}

		if(empty($yy_no)){
			throw new Exception("预约单号不能为空！");
		}

		$sql = "select * from zys_member where user_id = '".$user_id."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception('用户不存在');
		}
		$sql="select sid,code,sname from zys_shippingline where sid='".$sid."'";
		$row=$db->getRow($sql);
		if(empty($row)){
			throw new Exception("船名不能为空！");
		}

		$data = array(
			'user_id'=>$user_id,
			'vhccode'=>$vhccode,
			'tel'=>$tel,
			'box'=>$box,
			'quantity'=>$quantity,
			'ship_id'=>$sid,
			'ship_code'=>$row['code'],
			'company'=>$row['sname'],
			'station'=>$station,
			'ship_name'=>$ship_name,
			'voyage'=>$voyage,
			'bill'=>$bill,
			'th_time'=>gmstr2time($th_time),
			'add_time'=>gmtime()
		);

		$cc=substr($box, 0,2);
		$xx=substr($box, 2,2);

		$m=&m("member");
		$user=$m->get($uid);

		$url=APIURL.'flag=M&cus_no='.$row['code'].'&cc='.$cc.'&xx='.$xx.'&qty='.$quantity.'&cz_no='.$station.'&yy_no='.$yy_no.'&td_no='.$bill.'&ship_no='.$ship_name.'&ovoy='.$voyage.'&tx_dd='.urlencode($th_time).'&rem='.urlencode($rem).'&plate_no='.urlencode($vhccode).'&tel='.$tel.'&usr='.$user['user_name'];

		$retval=file_get_contents(trim($url));
		$retval=json_decode($retval,true);
		if(empty($retval)){
			throw new Exception("操作失败，请重试！");
		}

		$rut=$retval['ClientRut'][0][0];
		if(empty($rut)){
			throw new Exception("操作失败，请重试！");
		}

		if(empty($rut['flag'])){
			throw new Exception($rut['rem']);
		}

		//调接口  todo
		$reserve_mod  = &m('reservebox');
		if (!$rid = $reserve_mod->add($data))
		{
			throw new Exception($reserve_mod->get_error());
		}else{
			$status=1;
			$list = array('rid'=>$rid,'boxno'=>'');
		}

	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 * 预约订单列表
 * @param $pars
 */
function orderlistbox($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		$t=$pars->t?$pars->t:0;

		$row=$pars->row?$pars->row:0;
		$size=$pars->size?$pars->size:1;

		if(empty($uid))
		throw new Exception("用户不存在！");
		$sql = "select * from zys_member where user_id = '".$uid."'";
		$row1 = $db->getRow($sql);
		if(empty($row1)){
			throw new Exception('用户不存在');
		}

		$sqlw="1=1";
		if($t==0){
			$sqlw.=" and rcode=''";
		}
		if($t==1){
			$sqlw.=" and rcode!=''";
		}

		$result = $db->getAll("select * from zys_reservebox where $sqlw and user_id='".$uid."' order by add_time desc limit $row,$size");
		foreach($result as $k=>$v){
			if($v['th_time']){
				$result[$k]['th_time'] = local_date('Y-m-d H:i:s',$v['th_time']);
			}
			if($v['add_time']){
				$result[$k]['add_time'] = local_date('Y-m-d H:i:s',$v['add_time']);
			}
		}
		$status=1;
		$list = $result;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

function addbox($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		$wmtid=$pars->wmtid?$pars->wmtid:0;
		$boxno=$pars->boxno?$pars->boxno:'';
		$sealno=$pars->sealno?$pars->sealno:'';
		$box=$pars->box?$pars->box:'';
		$pic=$pars->pic?$pars->pic:'';
		if(empty($uid)){
			throw new Exception("用户不存在！");
		}

		if(empty($box)){
			throw new Exception("请选择箱型");
		}

		if(empty($boxno)){
			throw new Exception("请输入箱号");
		}

		if(empty($sealno)){
			throw new Exception("请输入封号");
		}

		if(empty($pic)){
			throw new Exception("请拍照");
		}
			
		$sql="select 1 from zys_waybill_main where wm_tid=".$wmtid;
		$w=$db->getOne($sql);
		if(!$w){
			throw new Exception("运单不存在！");
		}

		$sql="insert into zys_waybill_box set wmtid='".$wmtid."',box='".$box."',boxno='".$boxno."',sealno='".$sealno."',pic='".$pic."',add_time='".gmtime()."'";
		$db->query($sql);

		if (checkUrl(SOAP_URL)) {
			$client = new SoapClient(SOAP_URL);

			$db =& db();
			$sql = "select wm_code from zys_waybill_main where wm_tid=" . $wmtid;
			$code = $db->getOne($sql);
			if ($code) {
				$a='';
				$pa=explode(',', $pic);
				
				if($pa){
					foreach ($pa as $v){
						if($v){
							$a.=SITE_URL.'/'.$v.',';
						}
					}
				}
				
				$param = array();
				$param['Code'] = $code;
				$param['address'] = trim($a,',');
				$param['xmode'] = $box;
				$param['xnumber'] = $boxno;
				$param['feng'] = $sealno;

				$response = $client->__soapCall("xiang", array($param));
				$response = json_decode($response->xiangResult, true);
			}
		}

		$status =1;
		$list = $sc;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

function boxn($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		$wmtid=$pars->wmtid?$pars->wmtid:0;

		if(empty($uid)){
			throw new Exception("用户不存在！");
		}
			
		$sql="select s.g_box from zys_waybill_sub_trunk t
INNER JOIN zys_goods_trunk_sub s on t.ws_gstid=s.gs_tid
where ws_wmtid=".$wmtid;

		$list=$db->getAll($sql);

		$status =1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


function getbox($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		$wmtid=$pars->wmtid?$pars->wmtid:0;

		if(empty($uid)){
			throw new Exception("用户不存在！");
		}
			
		$sql="select box,boxno,sealno,pic from zys_waybill_box where wmtid=".$wmtid;
		$list=$db->getAll($sql);

		$status =1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 添加编辑用户
 * @param $pars
 * @return string
 */
function add_user($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$user_id=$pars->user_id?$pars->user_id:'';//用户id
		$user_name=$pars->user_name?$pars->user_name:'';//用户名
		$real_name=$pars->real_name?$pars->real_name:'';//用户名
		$phone_tel=$pars->phone_tel?$pars->phone_tel:'';//电话

		if(empty($user_name)){
			throw new Exception("用户不能为空！");
		}

		$sql = "select * from zys_member where user_name = '".$user_name."'";
		$row = $db->getRow($sql);
		if(!empty($row) && $user_id==0){
			throw new Exception("用户名已存在！");
		}
		if($user_id==0){
			$password = trim('123456');

			if (strlen($user_name) < 3 || strlen($user_name) > 25) {
				throw new Exception("请输入3-25位用户名！");
			}

			if (!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", $phone_tel)) {
				throw new Exception("请输入正确手机号！");
			}

			$data =array(
                'user_name' =>$user_name,
                'password' =>$password,
                'phone_tel' =>$phone_tel,
                'phone_mob' =>$phone_tel,
                'real_name' =>$real_name
			);

			/* 检查名称是否已存在 */
			if (check_username($user_name)) {
				throw new Exception("用户名已存在！");
			}

			$model_member =& m('member');
			$user_id = $model_member->add($data);
			if (!$user_id)
			{
				throw new Exception($model_member->get_error());
			}

			$priv = '';
			$data = array(
                'user_id' => $user_id,
                'store_id' => '0',
                'privs' => $priv,
			);

			$admin_mod = & m('userpriv');
			$admin_id = $admin_mod->add($data);
			if(!$admin_id){
				throw new Exception($admin_mod->get_error());
			}
		}else{

			if (strlen($user_name) < 3 || strlen($user_name) > 25) {
				throw new Exception("请输入3-25位用户名！");
			}

			if (!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", $phone_tel)) {
				throw new Exception("请输入正确手机号！");
			}

			$data =array(
                'user_name' =>$user_name,
                'phone_tel' =>$phone_tel,
                'phone_mob' =>$phone_tel,
			);

			$model_member =& m('member');
			$user_id = $model_member->edit($user_id,$data);
		}

		$status =1;
		$list = array('user_id'=>$user_id,'user_name'=>$user_name,'phone_tel'=>$phone_tel);
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 *运程方案
 * @param $pars
 * @return string
 */
function haul_main($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$user_id=$pars->user_id?$pars->user_id:'';//用户id
		$tid=$pars->tid?$pars->tid:0;//运程方案主键
		$w_tid=$pars->w_tid?$pars->w_tid:0;
		$zhdm_type=$pars->zhdm_type?$pars->zhdm_type:'';//业务类型
		$zhdm_name=$pars->zhdm_name?$pars->zhdm_name:'';//运程方案名称
		$zhdm_consignor=$pars->zhdm_consignor?$pars->zhdm_consignor:'';//货主
		$zhdm_note=$pars->zhdm_note?$pars->zhdm_note:'';//备注
		$haul=$pars->haul?$pars->haul:'';
		if(empty($user_id))
		throw new Exception("用户不存在！");
		$sql = "select * from zys_member where user_id = '".$user_id."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception("用户不存在！");
		}
		if(empty($zhdm_type)){
			throw new Exception("请填写业务类型！");
		}
		if(empty($zhdm_name)){
			throw new Exception("请填写运程方案名称！");
		}
		if(empty($zhdm_consignor)){
			throw new Exception("请填写货主！");
		}
		if(empty($haul)){
			throw new Exception("请填写运程定义！");
		}

		if (!empty ($haul)) {
			$haul = json_decode(json_encode($haul),true);
		}

		$data = array(
            'zhdm_name' => $zhdm_name,
            'zhdm_type'  => $zhdm_type,
            'zhdm_otid'  => $row['unit'],
            'zhdm_consignor' => $zhdm_consignor,
            'zhdm_note' => $zhdm_note,
            'zhdm_time' => gmtime(),
            'zhdm_userid' => $row['user_id'],
            'zhdm_w_id' => $w_tid
		);

		$haul_define_main =  & m ('haul_define_main');

		if($tid){
			$haul_define_main->edit($tid, $data);
			if($haul_define_main->has_error()){
				throw new Exception($haul_define_main->get_error());
			}
		}else{
			//添加
			$tid = $haul_define_main->add($data);
			if(empty($tid)){
				throw new Exception('添加失败');
			}
		}

		$haul_define_mod = & m ('haul_define');
		$haul_define_collect_mod = &m('haul_define_collect');
		if($haul){
			foreach ($haul as $k=>$v){
				$date = gmstr2time($v['h_date']);
				$haul_sub = array(
                    'h_zhdmtid' => $tid,
                    'h_short_name' => $v['h_short_name'],
                    'h_name' => $v['h_name'],
                    'h_type'  => intval($v['h_type']),
                    'h_linkman'  => $v['h_linkman'],
                    'h_linkman_tel'  => $v['h_linkman_tel'],
                    'h_date'  => $date,
                    'h_address'  => $v['h_address'],
                    'h_order'  => intval($v['h_order']),
                    'h_range'  => intval($v['h_range']),
                    'h_required'  => intval($v['h_required']),
                    'h_w_id'  => intval($v['h_w_tid']),
				);
				if($v['h_tid']){
					//修改
					$h_tid = $v['h_tid'];
					$haul_define_mod->edit($h_tid, $haul_sub);
					if ($haul_define_mod->has_error())
					{
						throw new Exception($haul_define_mod->get_error());
					}
				}else{
					//添加
					$h_tid = $haul_define_mod->add($haul_sub);
					if(empty($h_tid)){
						throw new Exception('添加失败');
					}
				}
				$item = json_decode(json_encode($v['item']),true);
				if($item){
					foreach ($item as $kk=>$vv){
						$haul_collect = array(
                            'hc_h_tid' => $h_tid,
                            'h_collect_type' => intval($vv['h_collect_type']),
                            'h_collect_des' =>  $vv['h_collect_des'],
                            'h_collect_val' =>  $vv['h_collect_val'],
                            'h_collect_w_id' =>  $vv['hc_w_tid'],
						);
						if($vv['hc_tid']){
							//修改
							$haul_define_collect_mod->edit($vv['hc_tid'],$haul_collect);
							if ($haul_define_collect_mod->has_error())
							{
								throw new Exception($haul_define_collect_mod->get_error());
							}
						}else{
							//添加
							$hc_tid = $haul_define_collect_mod->add($haul_collect);
							if(empty($hc_tid)){
								throw new Exception('添加失败');
							}
						}
					}
				}
				unset($haul_sub);
			}
		}
		$status =1;

		$sql = "select h_tid,h_w_id from zys_haul_define where h_zhdmtid='".$tid."'";
		$defines = $db->getAll($sql);
		foreach ($defines as $k=>$v){
			$hc_h_tid = $v['h_tid'];
			$sql = "select hc_tid,h_collect_w_id from zys_haul_define_collect where hc_h_tid='".$hc_h_tid."'";
			$defines[$k]['sub'] = $db->getAll($sql);
		}
		$list = array('main_id'=>$tid,'w_main_id'=>$w_tid,'item'=>$defines);
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

//删除主运程
function del_haul_main($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$tid=$pars->tid?$pars->tid:0;//运程方案主键
		if(empty($tid)){
			throw new Exception('请求数据不存在');
		}

		$sql_haul = "select * from zys_haul_define_main where zhdm_tid ='".$tid."'";
		$row = $db->getRow($sql_haul);
		if(empty($row)){
			throw new Exception('请求数据不存在');
		}

		$sql = "select h_tid from zys_haul_define where h_zhdmtid ='".$tid."'";
		$h_tids = $db->getAll($sql);
		foreach($h_tids as $val){
			$h_tid = $val['h_tid'];

			$sql_haul_define_collect = "delete from zys_haul_define_collect where hc_h_tid=".$h_tid;
			$db->query($sql_haul_define_collect);

			$sql_haul_define = "delete from zys_haul_define where h_tid=".$h_tid;
			$db->query($sql_haul_define);
		}
		$sql_haul = "delete from zys_haul_define_main where zhdm_tid ='".$tid."'";
		$result = $db->query($sql_haul);

		if ($result) {
			$list = array('main_id'=>$tid);
		}
		$status =1;

	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

//删除运程定义
function del_haul_define($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$h_tid=$pars->tid?$pars->tid:0;//运程定义主键

		if(empty($h_tid)){
			throw new Exception('请求数据不存在');
		}

		$sql = "select * from zys_haul_define where h_tid=".$h_tid;
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception('请求数据不存在');
		}

		$sql = "delete from zys_haul_define_collect where hc_h_tid=".$h_tid;
		$db->query($sql);

		$sql = "delete from zys_haul_define where h_tid=".$h_tid;
		$result =  $db->query($sql);

		if ($result) {
			$list = array('main_id'=>$h_tid);
		}
		$status =1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

//删除运程采集
function del_haul_collect($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$h_tid=$pars->tid?$pars->tid:0;//运程采集主键

		if(empty($h_tid)){
			throw new Exception('请求数据不存在');
		}

		$sql = "select * from zys_haul_define_collect where hc_tid=".$h_tid;
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception('请求数据不存在');
		}

		$sql = "delete from zys_haul_define_collect where hc_tid=".$h_tid;
		$result = $db->query($sql);

		if ($result) {
			$list = array('main_id'=>$h_tid);
		}
		$status =1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 * 围栏管理
 * @param $pars
 * @return string
 */
function rail_define($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$id = $pars->id?$pars->id:0;
		$name = $pars->name?$pars->name:'';
		$lat = $pars->lat?$pars->lat:'';
		$lng = $pars->lng?$pars->lng:'';
		$offset = $pars->offset?$pars->offset:'';
		$status = $pars->status?$pars->status:'';
		if(empty($name)){
			throw new Exception("请填写名称！");
		}
		if(empty($lat)){
			throw new Exception("请填写经度！");
		}
		if(empty($lng)){
			throw new Exception("请填写纬度！");
		}
		if(empty($offset)){
			throw new Exception("请填写区域半径！");
		}

		$data = array(
            'name' => $name,
            'lat' => $lat,
            'lng' => $lng,
            'offset' => $offset,
            'status' => $status
		);

		$rail_define_mod =  & m ('rail_define');

		if($id){
			$rail_define_mod->edit($id, $data);
			if($rail_define_mod->has_error()){
				throw new Exception($rail_define_mod->get_error());
			}
		}else{
			//添加
			$id = $rail_define_mod->add($data);
			if(empty($id)){
				throw new Exception('添加失败');
			}
		}
		$status =1;
		$list = array('main_id'=>$id);
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 删除围栏
 * @param $pars
 * @throws Exception
 */
function del_rail($pars){
	$status=0;
	try {
		$db = &db();
		$list = array();
		$id = $pars->id ? $pars->id : 0;
		if (empty($id)) {
			throw new Exception("请求数据不存在！");
		}
		$db = &db();
		$sql = "select * from zys_rail_define where id='" . $id . "'";
		$row = $db->getRow($sql);
		if (empty($row)) {
			throw new Exception("请求数据不存在！");
		}
		$sql = "delete from zys_rail_define where id='" . $id . "'";
		$result = $db->query($sql);
		if ($result) {
			$list = array('main_id' => $id);
		}
		$status = 1;
	}catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 船公司
 * @param $pars
 * @return string
 */
function company($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		$key=$pars->key?$pars->key:'';
		if(empty($uid))
		throw new Exception("用户不存在！");
		$condition = '1=1';
		if(!empty($key)){
			$condition.=" 	and (code like '%".$key."%' || sname like '%".$key."%' ) ";
		}
		$sql="select sid,code,sname from  zys_shippingline where $condition order by sort_order asc,add_time desc";
		$sc=$db->getAll($sql);
		$status =1;
		$list = $sc;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 场站
 * @param $pars
 * @return string
 */
function station($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		if(empty($uid))
		throw new Exception("用户不存在！");
		$sql="select d_key,d_value from  zys_dictionary where d_code = 'station_code' and d_del=1 order by d_order asc";
		$sc=$db->getAll($sql);;
		$status =1;
		$list = $sc;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 箱型
 * @param $pars
 * @return string
 */
function box($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		if(empty($uid))
		throw new Exception("用户不存在！");
		$sql="select d_key,d_value from  zys_dictionary where d_code = 'boxtype' and d_del=1 order by d_order asc";
		$sc=$db->getAll($sql);
		$status =1;
		$list = $sc;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 验证是否可以预约
 * @param $pars
 * @return string
 */
function check($pars){
	$status=0;
	try{
		$db = &db();
		$list = array('if_order'=>0);
		$uid=$pars->uid?$pars->uid:0;
		$sid=$pars->sid?intval($pars->sid):0;//船公司
		$station=$pars->station?$pars->station:'';//场站
		$box=$pars->box?$pars->box:'';//箱型
		$quantity=$pars->quantity?$pars->quantity:'';//箱量
		if(empty($uid))
		throw new Exception("用户不存在！");
		if(empty($sid))
		throw new Exception("船名不能为空！");

		if(empty($station)){
			throw new Exception("场站不能为空！");
		}
		if(empty($box)){
			throw new Exception("箱型不能为空！");
		}
		if(empty($quantity)){
			throw new Exception("箱量不能为空！");
		}

		$sql = "select * from zys_member where user_id = '".$uid."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception('用户不存在');
		}
		$sql="select sid,code,sname from  zys_shippingline where sid='".$sid."'";
		$row=$db->getRow($sql);
		if(empty($row)){
			throw new Exception("船公司不存在！");
		}

		$cc=substr($box, 0,2);
		$xx=substr($box, 2,2);

		$m=&m("member");
		$user=$m->get($uid);

		$url=APIURL.'flag=C&cus_no='.$row['code'].'&cc='.$cc.'&xx='.$xx.'&qty='.$quantity.'&cz_no='.$station.'&yy_no=&td_no=&ship_no=&ovoy=&tx_dd=
		&rem=&plate_no=&tel=&usr='.$user['user_name'];

		$retval=file_get_contents($url);
		$retval=json_decode($retval,true);
		if(empty($retval)){
			throw new Exception("操作失败，请重试！");
		}

		$rut=$retval['ClientRut'][0][0];
		if(empty($rut)){
			throw new Exception("操作失败，请重试！");
		}

		if(empty($rut['flag'])){
			throw new Exception($rut['rem']);
		}


		//调接口  todo
		$status=1;
		$list = array('if_order'=>1,'yy_no'=>$rut['yy_no']);
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 下预约订单
 * @param $pars
 */
function add_order($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$user_id=$pars->uid?$pars->uid:0;
		$vhccode=$pars->vhccode?$pars->vhccode:'';//车牌号
		$tel=$pars->tel?$pars->tel:'';//电话
		$sid=$pars->sid?intval($pars->sid):0;
		$station=$pars->station?$pars->station:'';//场站
		$box=$pars->box?$pars->box:'';//箱型
		$quantity=$pars->quantity?$pars->quantity:'';//箱量
		$ship_name=$pars->ship_name?$pars->ship_name:'';//船名
		$voyage=$pars->voyage?$pars->voyage:'';//船次
		$bill=$pars->bill?$pars->bill:'';//提单号
		$th_time=$pars->th_time?$pars->th_time:'';//提货时间
		$yy_no=$pars->yy_no?$pars->yy_no:'';//预约单号
		$rem=$pars->rem?$pars->rem:'';//备注
		if(empty($user_id))
		throw new Exception("用户不存在！");
		if(empty($sid))
		throw new Exception("船名不能为空！");

		if(empty($station)){
			throw new Exception("场站不能为空！");
		}
		if(empty($box)){
			throw new Exception("箱型不能为空！");
		}
		if(empty($quantity)){
			throw new Exception("箱量不能为空！");
		}
		if(empty($vhccode)){
			throw new Exception("车牌号不能为空！");
		}
		if(empty($tel)){
			throw new Exception("电话不能为空！");
		}
		if(empty($ship_name)){
			throw new Exception("船名不能为空！");
		}
		if(empty($voyage)){
			throw new Exception("船次不能为空！");
		}
		if(empty($bill)){
			throw new Exception("提单号不能为空！");
		}
		if(empty($th_time)){
			throw new Exception("提货时间不能为空！");
		}

		if(empty($yy_no)){
			//throw new Exception("预约单号不能为空！");
		}

		$sql = "select * from zys_member where user_id = '".$user_id."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception('用户不存在');
		}
		$sql="select sid,code,sname from  zys_shippingline where sid='".$sid."'";
		$row=$db->getRow($sql);
		if(empty($row)){
			throw new Exception("船名不能为空！");
		}

		$data = array(
			'user_id'=>$user_id,
			'vhccode'=>$vhccode,
			'tel'=>$tel,
			'box'=>$box,
			'quantity'=>$quantity,
			'ship_id'=>$sid,
			'ship_code'=>$row['code'],
			'company'=>$row['sname'],
			'station'=>$station,
			'ship_name'=>$ship_name,
			'voyage'=>$voyage,
			'bill'=>$bill,
			'th_time'=>gmstr2time($th_time),
			'add_time'=>gmtime(),
			'yy_no'=>$yy_no,
		);

		$cc=substr($box, 0,2);
		$xx=substr($box, 2,2);

		$m=&m("member");
		$user=$m->get($uid);

		$url=APIURL.'flag=M&cus_no='.$row['code'].'&cc='.$cc.'&xx='.$xx.'&qty='.$quantity.'&cz_no='.$station.'&yy_no='.$yy_no.'&td_no='.$bill.'&ship_no='.$ship_name.'&ovoy='.$voyage.'&tx_dd='.urlencode($th_time).'&rem='.urlencode($rem).'&plate_no='.urlencode($vhccode).'&tel='.$tel.'&usr='.$user['user_name'];

		$retval=file_get_contents(trim($url));
		$retval=json_decode($retval,true);
		if(empty($retval)){
			throw new Exception("操作失败，请重试！");
		}

		$rut=$retval['ClientRut'][0][0];
		if(empty($rut)){
			throw new Exception("操作失败，请重试！");
		}

		if(empty($rut['flag'])){
			throw new Exception($rut['rem']);
		}

		//调接口  todo
		$reserve_mod  = &m('reserve');
		if (!$rid = $reserve_mod->add($data))
		{
			throw new Exception($reserve_mod->get_error());
		}else{
			$status=1;
			$list = array('rid'=>$rid);
		}

	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}


/**
 * 预约订单列表
 * @param $pars
 */
function order_list($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$uid=$pars->uid?$pars->uid:0;
		$t=$pars->t?$pars->t:0;

		$row=$pars->row?$pars->row:0;
		$size=$pars->size?$pars->size:1;

		if(empty($uid))
		throw new Exception("用户不存在！");
		$sql = "select * from zys_member where user_id = '".$uid."'";
		$row1 = $db->getRow($sql);
		if(empty($row1)){
			throw new Exception('用户不存在');
		}

		$sqlw="1=1";
		if($t==0){
			$sqlw.=" and rcode=''";
		}
		if($t==1){
			$sqlw.=" and rcode!=''";
		}
		$reserve_mod  = &m('reserve');
		$result = $reserve_mod->getAll("select * from zys_reserve where $sqlw and user_id='".$uid."' order by add_time desc limit $row,$size");
		foreach($result as $k=>$v){
			if($v['th_time']){
				$result[$k]['th_time'] = local_date('Y-m-d H:i:s',$v['th_time']);
			}
			if($v['add_time']){
				$result[$k]['add_time'] = local_date('Y-m-d H:i:s',$v['add_time']);
			}
		}
		$status=1;
		$list = $result;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 外部接口调用接口
 * @param $pars
 * @return string
 */
function order($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$user_name=$pars->user_name?$pars->user_name:'';
		$add_time_from=$pars->add_time?$pars->add_time:'';
		$add_time_to=$pars->to_time?$pars->to_time:'';
		if(empty($user_name))
		throw new Exception("用户不存在！");
		$sql = "select * from zys_member where user_name = '".$user_name."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception("用户不存在！");
		}
		$condition = '';
		if(!empty($add_time_from)){
			$add_time_from = gmstr2time($add_time_from);
			$condition.=" and add_time >= $add_time_from";
		}
		if(!empty($add_time_to)){
			$add_time_to = gmstr2time_end($add_time_to);
			$condition.=" and add_time <= $add_time_to";
		}
		$reserve_mod  = &m('reserve');
		$result = $reserve_mod->getAll("select * from zys_reserve where rcode='' and user_id='".$row['user_id']."' $condition");
		foreach($result as $k=>$v){
			if($v['th_time']){
				$result[$k]['th_time'] = local_date('Y-m-d H:i:s',$v['th_time']);
			}
			if($v['add_time']){
				$result[$k]['add_time'] = local_date('Y-m-d H:i:s',$v['add_time']);
			}
		}
		$status=1;
		$list = $result;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 更新预约订单
 * @param $pars
 * @return string
 */
function update_order($pars){
	$status=0;
	try{
		$db = &db();
		$list = array();
		$rid=$pars->rid?$pars->rid:'';
		$rcode=$pars->rcode?$pars->rcode:'';
		$contact_tel = $pars->contact_tel?$pars->contact_tel:'';
		$sql = "select * from zys_reserve where yy_no='".$rid."'";
		$row = $db->getRow($sql);
		if(empty($row)){
			throw new Exception("预约订单不存在！");
		}
		$sql ="update zys_reserve set rcode='".$rcode."',contact_tel='".$contact_tel."' where yy_no='".$rid."'";
		$db->query($sql);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult2($status,$list);
}
/**
 *
 * 用户登录
 * @param unknown_type $account 登录名称
 * @param unknown_type $psw   密码
 * @param unknown_type $region 用户当前所在区域
 * @param unknown_type $pars
 */

function login($pars){
	$status=0;
	try{
		if(property_exists($pars,'a'))
		$account=$pars->a?$pars->a:'';
		if(property_exists($pars,'t'))
		$account=$pars->t?$pars->t:'';
		$psw=$pars->p?$pars->p:'';
		$region=property_exists($pars,"r")?$pars->r[0]:'';

		if(empty($account))
		throw new Exception("用户名不能为空！");
		if(empty($psw))
		throw new Exception("密码不能为空！");

		if(empty($pars->rnd)){
			throw new Exception("用户设备号不能为空！");
		}

		$a_member=&m("member");
		$user=$a_member->get(array(
		 'fields'   => "user_name,real_name,phone_tel,birthday,gender,headimgurl
		 				,logins,islogin,del,password,current_waybill,uuid,vhcCode",
         'conditions'  => "user_name='".$account."'",
         'limit'   => 1,
		));
		if(empty($user)){
			//			$randCharObj =new RandChar();
			//			throw new Exception($randCharObj->getRandChar(20));
			throw new Exception("用户没有注册");
		}else{
			if(md5($psw)!=$user['password']){
				throw new Exception("用户密码错误");
			}
			if($user['del']){
				throw new Exception("用户已经被禁用，如有问题请联系客服！");
			}
			//单例登录
			/*/------------------------------------
			 $u=$a_member->get($user["user_id"]);
			 if($u['sn']!=$pars->rnd){
				if(!empty($u['channelId'])){
				pushMsg($u['channelId'], "{\"type\":\"-1\",\"result\":\"当前客户端已在其它终端登录\" }",0);
				}}*/
			//------------------------------------
			$data = array();
			$data['last_login']=gmtime();
			$data['logins']=$user['logins']+1;
			$data['islogin']=1;
			$data['sn']=$pars->rnd;
			$data['channelId']='';
			$data['device_type']=trim($pars->system);
			$a_member->edit($user["user_id"],$data);
			$user["site_url"]=SITE_URL;
			$user["config_url"]=CONFIG_URL;
			$user["site_url"]=SITE_URL;
			$pars->uid=$user["user_id"];
			//认证信息
			$auth=&m('auth');
			$authRnt=$auth->authStatus($user["user_id"]);
			if(empty($authRnt)===false)
			$user['auth_real']= $authRnt['auth_real'];
			$user['auth_vhc']= $authRnt['auth_vhc'];
			$user['auth_operator']= $authRnt['auth_operator'];
			$user['loadconfig'] = true;  //更新配置信息;
			if( SPLASH){
				$user['SPLASH']=array('sdate'=>SPLASH_SDATE,'edate'=>SPLASH_EDATE,'image'=>SPLASH_IMG);
			}
			$status=1;
		}
	}
	catch (Exception $exp){
		$user=$exp->getMessage();
	}
	return JSONResult($status,$user,$pars);
}

function logout($pars){
	$status=0;
	try{
		$a_member=&m("member");
		$data=array('channelId'=>'','device_type'=>'','islogin'=>0,'sn'=>'');
		$a_member->edit($pars->uid,$data);
		$status=1;
		$user="注销成功";
	}
	catch (Exception $exp){
		$user=$exp->getMessage();
	}
	return JSONResult($status,$user,$pars);
}
/**
 * 获取用户基本信息（账户个人等级，评分等）
 * @param unknown_type $pars
 */
function getuserbase($pars){
	$db =&db();
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		if(empty($pars->user_name)){
			throw new Exception('当前人员不存在');
		}

		$sql="SELECT headimgurl,case when ifnull(real_name,'')<>'' then real_name else user_name end as real_name FROM cw_member where user_name='$pars->user_name'";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('人员不存在');
		}

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 *
 * 获取验证码
 * @param unknown_type $tel
 * @param unknown_type $pars
 */
function authcode($pars){
	$status=0;
	try{
		$tel=$pars->t?$pars->t:'';
		if(property_exists($pars,"type"))
		$type=$pars->type?$pars->type:'注册';
		else
		$type="注册";

		$a_mod =&m('authcode');
		if(empty($tel) or strlen(strval($tel))!=11)
		throw new Exception("手机号码不正确");
		if(!empty($type)&&$type==="注册"){
			$a_member=&m("member");
			if(!$a_member->unique($tel)){
				throw new Exception("当前手机号码已注册");
			}
		}

		if(!empty($type)&&$type==="找回密码"){
			$a_member=&m("member");
			if($a_member->unique($tel)){
				throw new Exception("当前手机号码未注册");
			}
		}
		$data = array();
		$data['a_status']  =  1;
		$econdition="a_tel='".$tel."' and ifnull(a_type,'注册')='".$type."'";
		$a_mod->edit($econdition,$data);
			
		$code=substr(strval(rand(10000,99999)),0,6);
		$data = array();
		$data['a_tel']  =  $tel;
		$data['a_code'] =   $code;
		$data['a_type'] =   $type;
		$data['a_date']  =   gmtime();
		if (!$article_id = $a_mod->add($data))
		{
			throw new Exception($a_mod->get_error());
		}
		//发送短信
		//smsSend('短信验证码：'.$code.'。',$tel);
		smsSend('APP验证码：'.$code."【宏思美旭】",$tel);

		$status=1;
		$list=array("code"=>'');
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 *
 * 检测验证码有效性
 * @param unknown_type $tel
 * @param unknown_type $code
 * @param unknown_type $type 验证码类型
 * @param unknown_type $pars*/
function valiAuthcode($pars){
	$status=0;
	try{
		$tel=$pars->t?$pars->t:'';
		$code=$pars->c?$pars->c:'';
		if(property_exists($pars,"type"))
		$type=$pars->type?$pars->type:'注册';
		else
		$type="注册";

		PrivateAuthcode($tel,$code,$type);

		$status=1;
		$list="验证成功";

	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 *
 * 内部使用，校验验证码有效性
 * @param unknown_type $tel
 * @param unknown_type $code
 * @param unknown_type $type 验证码类型
 * @param unknown_type $pars*/
function PrivateAuthcode($tel,$code,$type="注册"){
	$status=0;
	try{
		$a_mod =&m('authcode');
		if(empty($tel) or strlen(strval($tel))!=11)
		throw new Exception("手机号码不正确");
		if(!empty($type)&&$type==="注册"){
			$a_member=&m("member");
			if(!$a_member->unique($tel)){
				throw new Exception("当前手机号码已注册");
			}
		}
		$intervl=15*60;  //15分钟
		$code=$a_mod->get(array(
        'conditions'  => "a_tel='".$tel."' and a_code='".$code."' and ifnull(a_type,'注册')='".$type."' and a_status=0",
	        'limit'   => 1,
	        'order'   => 'a_date  DESC', //必须加别名
		));

		if(empty($code)){
			throw new Exception("验证码无效");
		}

		if(gmtime()-$code['a_date']>$intervl){
			throw new Exception("验证码已过期");
		}

		$status=1;
		$list="验证成功";

	}
	catch (Exception $exp){
		throw new Exception($exp->getMessage());
	}
}

/**
 * 注册
 * @param unknown_type $tel  登录名 （手机号)
 * @param unknown_type $code 验证码
 * @param unknown_type $psw 密码
 * @param unknown_type $region 用户所在区域
 * @param unknown_type $pars
 * */

function reg($tel,$code,$psw,$pars){
	$status=0;
	try{
		$a_mod =&m('authcode');
		if(empty($tel) or strlen(strval($tel))!=11)
		throw new Exception("手机号码不正确");
		$a_member=&m("member");
		if(!$a_member->unique($tel)){
			throw new Exception("当前手机号码已注册");
		}

		PrivateAuthcode($tel,$code,'注册');

		if(empty($psw))
		throw new Exception("密码不能为空！");
		if(strlen($psw)<6)
		throw new Exception("密码长度至少是6位！");

		$data = array();
		$data['a_status']  =  1;
		$a_mod->edit($code, $data);
		$a_member=&m("member");
			

		$data = array();
		$randCharObj =new RandChar();
		$data['uuid']=$randCharObj->getRandChar(20);
		$data['user_name']      =  $tel;
		$data['phone_tel']    =   $tel;
		$data['password']   =   md5($psw);
		$data['reg_time']   =  gmtime();
		//$data['user_level']   =  $type;
		$data['real_name']   =  "用户".rand(1000000, 9999999);
		$data['sn']   =$pars->rnd;
			
		if (!$user_id = $a_member->add($data))
		{
			throw new Exception($a_member->get_error());
		}else{

			//regUser2Openfire("http://192.168.0.189:9090",$data['user_name'],"888128");

			return login($pars);
		}
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 *
 * 找回密码
 * @param unknown_type $pars
 */
function getpassword($pars){
	$status=0;
	$list="";
	try{
		$tel=$pars->tel;
		$code=$pars->code;
		PrivateAuthcode($tel,$code,'找回密码');
		$newPsw=$pars->newpsw;
		if(empty($newPsw))
		throw new Exception("密码不能为空！");
		if(strlen($newPsw)<6)
		throw new Exception("密码长度至少是6位！");
		$member_mod = &m("member");
		$user=$member_mod->get("phone_tel='$tel' or user_name='$tel'");
		if(empty($user)){
			throw new Exception("手机号未注册");
		}
		if($user['del'])
		throw new Exception("用户已被禁用");
			
		$data = array();
		$data['password']   =   md5($newPsw);
		$member_mod->edit($user['user_id'],$data);
		$status=1;
		$list="密码找回成功";
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 *
 * 设置密码
 * @param unknown_type $uid 用户编码
 * @param unknown_type $oldPsw 原始密码
 * @param unknown_type $newPsw 新密码
 * @param unknown_type $pars
 */
function password($pars){
	$status=0;
	$list="";
	try{
		$uid=$pars->uid;
		$oldPsw=$pars->oldpsw;
		$newPsw=$pars->newpsw;
		if(empty($oldPsw))
		throw new Exception("原始密码不能为空！");
		if(empty($newPsw))
		throw new Exception("密码不能为空！");
		if(strlen($newPsw)<6)
		throw new Exception("密码长度至少是6位！");
		$sql="select 1 FROM yk_member where user_id=".$uid." and password='".md5($oldPsw)."'";
		$member_mod = &m("member");
		$user=$member_mod->get_info($uid);
		if(empty($user)){
			throw new Exception("用户不存在");
		}
		if($user['password']!=md5($oldPsw)){
			throw new Exception("原始密码不正确！");
		}
		$data = array();
		$data['password']   =   md5($newPsw);
		$member_mod->edit("user_id=".$uid." and password='".md5($oldPsw)."'",$data);
		$status=1;
		$list="密码修改成功";
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 *
 * 注册推送CID
 * @param unknown_type $pars
 */
function igetui($pars){
	$status=0;
	$list="";
	try{
		$cid=$pars->cid;
		$uid=$pars->uid;
		$data = array();
		$data['igetui'] = $cid;
		$member_mod = &m("member");
		$user=$member_mod->get_info($uid);
		if(empty($user)){
			throw new Exception("用户不存在");
		}
		$member_mod->edit($uid,$data);
		$status=1;
		$list="成功";
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 * 获取字典数据
 * Enter description here ...
 * @param unknown_type $code 字典代码
 * @param unknown_type $pars
 * @throws Exception
 */
function getDictionary($code,$pars){
	$status=0;
	try{
		$dictionary =&m('dictionary');
		if(empty($code) )
		throw new Exception("字典代码不正确");
		$list=array_values($dictionary->find(array(
		       'fields'=>"d_key,d_value",
			   'conditions'=>"d_code='".$code."' and ifnull(d_del,0)=0",
		        'order'   => 'd_order  ASC'
		        )));
		        $status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 * 修改用户个人信息
 * Enter description here ...
 * @param unknown_type $u
 * @param unknown_type $pars
 * @throws Exception
 */
function editUser($u){
	$status=0;
	$data=array();
	try{
		$userId=$u->user_id;

		if(property_exists($u,'real_name')){
			$data["real_name"]=$u->real_name;
		}
		if(property_exists($u,"gender")){
			$data["gender"]=$u->gender;
		}
		if(property_exists($u,"phone_tel")){
			$data["phone_tel"]=$u->phone_tel;
		}
		if(property_exists($u,"birthday")){
			$data["birthday"]=$u->birthday;
		}
		if(property_exists($u,"avatar")){
			$data["headimgurl"]=$u->avatar;
		}
		if(property_exists($u,"sign")){
			$data["sign"]=$u->sign;
		}
		$a_member=&m("member");
		$a_member->edit($userId,$data);

		$list=$a_member->get(array(
		 'fields'   => 'user_name,real_name,phone_tel,birthday,gender,headimgurl,sign',
         'conditions'  => "user_id=".$userId,
         'limit'   => 1,
		));

		//		if(property_exists($u,'real_name')){
		//			editUser2Openfire("http://192.168.0.189:9090",$data['user_name'],$data["real_name"],"888128");
		//		}

		$status=1;

	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$u);

}

/**
 * 获取文章
 * Enter description here ...
 * @param unknown_type $pars
 * @throws Exception
 */
function getarticle($code,$pars){
	$status=0;
	try{
		$article_mod =&m('article');
		if(empty($code) )
		throw new Exception("文章不存在");
		$article_info=($article_mod->get("code='".$code."'"));
		$list=array();
		$list['article_id']=$article_info['article_id'];
		$list['title']=$article_info['title'];
		$list['link']=SITE_URL."/index.php?app=article&act=view&article_id=".$article_info['article_id'];
		$list['add_time']=local_date('Y-m-d H:i',$article_info['add_time']);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
/**
 * 上传文件
 * @throws Exception
 */
function uploadfile($file,$pars){
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$type=empty($pars->type)?'pic':$pars->type;
		if(!empty($file)&&!empty($file['name'])){
			$picname='';
			switch ($type)
			{
				case 'avatar':
					$picname=fileupload($file,'data/avatar','zys_',$pars->uid,false);
					break;
				case 'auth':
					$picname=fileupload($file,'data/auth','zys_',$pars->uid,false);
					break;
				case 'ex':
					$picname=fileupload($file,'data/ex_pic','zys_',$pars->uid,false);
					break;
				case 'ex_voice':
					$picname=fileuploadAudio($file,'data/ex_audio','zys_',$pars->uid,false);
				case 'haul_voice':
					$picname=fileuploadAudio($file,'data/haul_audio','zys_',$pars->uid,false);
					break;
				default:
					$picname=fileupload($file,'data/pic','zys_',$pars->uid,false);
			}
			//			if($type=='pic'){
			//				$picname=fileupload($file,'data/pic','cw_',$pars->uid,false);
			//			}else{
			//				$picname=fileuploadvideo($file,'data/video','cw_',$pars->uid,false);
			//			}
			$list=array('storename'=>str_replace('../', '', $picname),'orgname'=>$file['name']);
			$status=1;
		}
		else{
			$list="文件不存在";
		}
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}



/**
 * 获取广告列表
 * @param unknown_type $pars
 */
function adlist($pars){
	$db =&db();
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$row=$pars->row?$pars->row:0;
		$size=$pars->size?$pars->size:1;
		$position=$pars->position?$pars->position:'';
		$page=$pars->page?$pars->page:'';

		$sqlw="1=1";
		if($page){
			$sqlw.=" and ya_page='".$page."'";
		}
		if($position){
			$sqlw.=" and ya_position='".$position."'";
		}
		$sql="SELECT ya_tid,ya_pic,ya_title from yk_ad where ya_show=1 and $sqlw order by ya_order limit ".$row.",".$size;
		$list=$db->getAll($sql);
		$list=array_values($list);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 获取广告明细
 * @param unknown_type $pars
 */
function adinfo($pars){
	$db =&db();
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$ya_tid=$pars->ya_tid?intval($pars->ya_tid):0;
		if(empty($ya_tid)){
			throw new Exception('信息不存在');
		}

		$sql="SELECT ya_tid,ya_pic,ya_title,ya_content from yk_ad where ya_show=1 and ya_tid=".$ya_tid;
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('信息不存在');
		}

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 初始化支付
 * @param unknown_type $pars
 * @throws Exception
 */
function inipay($pars){
	$db =&db();
	$status=0;
	try{
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$desc=empty($pars->desc)?'':$pars->desc;
		if(empty($desc)){
			throw new Exception('缺少商品描述');
		}

		$bargainor_id=empty($pars->bargainor_id)?'':$pars->bargainor_id;
		if(empty($bargainor_id)){
			throw new Exception('缺少商户号');
		}

		$sp_billno=empty($pars->sp_billno)?'':$pars->sp_billno;
		if(empty($sp_billno)){
			throw new Exception('缺少内部订单号');
		}

		$total_fee=empty($pars->total_fee)?0:floatval($pars->total_fee);
		if(empty($total_fee)){
			throw new Exception('缺少总金额');
		}

		$sql="select o_status,o_paystatus from yk_order_xiche where o_uid=".$pars->uid." and o_code='".$sp_billno."'";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('订单不能支付');
		}

		if($list['o_status']!=CANPAY||$list['o_paystatus']=='已支付'){
			throw new Exception('订单不能支付');
		}

		$n_url="http://219.146.249.2:8008/didi/service/notify.php";
		$url="http://cl.tenpay.com/cgi-bin/wappayv2.0/wappay_init.cgi?ver=2.0&sale_plat=211&bank_type=0&notify_url=".$n_url."&attach=payorder";

		$url.="&desc=".$desc;
		$url.="&bargainor_id=".$bargainor_id;
		$url.="&sp_billno=".$sp_billno;
		$url.="&total_fee=".$total_fee;

		$sign=md5("attach=payorder&bank_type=0&bargainor_id=".$bargainor_id."&desc=".$desc."&notify_url=".$n_url."&sale_plat=211&sp_billno=".$sp_billno."&total_fee=".$total_fee."&ver=2.0&key=4d73c900fd124b328a97e4f4949e1c95");
		$sign=strtoupper($sign);
		$url.="&sign=".$sign;
		$result=file_get_contents($url);

		if(empty($result)){
			throw new Exception('支付失败');
		}

		$p = xml_parser_create();
		xml_parse_into_struct($p, $result, $vals, $index);
		xml_parser_free($p);
		$token_id='';
		$token_id=empty($vals[1]['value'])?'':$vals[1]['value'];

		if(empty($token_id)){
			throw new Exception('支付失败');
		}

		$list=array('token_id'=>$token_id);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 注册用户
 * @param unknown_type $url
 * @param unknown_type $user_name
 * @param unknown_type $secretKey
 * @throws Exception
 */
function regUser2Openfire($url,$user_name,$secretKey) {
	$postUrl = $url."/plugins/userService/users";
	$curlPost = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
		<user><username>".$user_name."</username><name>".$user_name."</name>
        <password>123</password>
        </user>";
	$options = array(
	CURLOPT_RETURNTRANSFER => TRUE,
	CURLOPT_HEADER         => TRUE,
	CURLOPT_NOBODY         => FALSE,
	CURLOPT_POST           => TRUE,
	CURLOPT_HTTPHEADER     => array("Authorization:".$secretKey,"Content-Type:application/xml" ),
	CURLOPT_POSTFIELDS     => $curlPost,
	);
	$ch = curl_init($postUrl);//初始化curl
	curl_setopt_array($ch,$options);
	$data = curl_exec($ch);//运行curl
	curl_close($ch);
	return $data;
}

function editUser2Openfire($url,$user_name,$name,$secretKey) {
	$postUrl = $url."/plugins/userService/users";
	$curlPost = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
		<user><username>".$user_name."</username><name>".$name."</name>
        </user>";
	$options = array(
	CURLOPT_RETURNTRANSFER => TRUE,
	CURLOPT_HEADER         => TRUE,
	CURLOPT_NOBODY         => FALSE,
	CURLOPT_PUT           => TRUE,
	CURLOPT_HTTPHEADER     => array("Authorization:".$secretKey,"Content-Type:application/xml" ),
	CURLOPT_POSTFIELDS     => $curlPost,
	);
	$ch = curl_init($postUrl);//初始化curl
	curl_setopt_array($ch,$options);
	$data = curl_exec($ch);//运行curl
	curl_close($ch);
	return $data;
}


/**
 * 用户设置区域
 * @param unknown_type $pars
 */
function usersetregion($pars){
	$db =&db();
	$status=0;
	try{
		$region_id=empty($pars->region_id)?0:$pars->region_id;
		$region_name=empty($pars->region_name)?'':$pars->region_name;
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}

		$sql="select * from cw_region where (region_id='$region_id' or -1='$region_id') and region_name='$region_name'";
		$region=$db->getRow($sql);
		if(empty($region)||empty($region_id)||empty($region_name)){
			throw new Exception('区域信息不准确');
		}

		$sql="update cw_member set cityid=$region[region_id],city='$region[region_name]' where user_type='app' and user_id=$pars->uid";
		$db->query($sql);
		$list='区域设置成功';
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
?>